/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月24日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.filter.smarthome.route;

import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jimi.app.dto.output.ApiOpenFunctionsOutputDto;
import com.jimi.gateway.utils.Constants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @FileName ShRouteMappingFilter.java
 * @Description: SmartHome路由映射过滤器，将外部请求的统一url根据method参数映射到具体地址上
 *
 * @Date 2017年4月24日 上午9:25:43
 * @author li.shangzhi
 * @version 1.0
 */
public class ShRouteMappingFilter extends ZuulFilter {

	public static final int FILTER_ORDER = 1;

	private final Logger logger = LoggerFactory.getLogger(ShRouteMappingFilter.class);

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		String routeId = String.valueOf(ctx.get("proxy"));
		if (!Constants.SMARTHOME_NAMESPACE.equals(routeId)) {
			return false;
		}
		return (ctx.getRouteHost() != null && ctx.sendZuulResponse()) && ctx.getBoolean(Constants.IS_NEXT_FILTER, true);
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		logger.info("请求的的客户信息为：{}", ctx.get("zuulRequestHeaders"));
		logger.info("请求的环境为：{}", ctx.get("proxy"));
		ApiOpenFunctionsOutputDto outputDto = (ApiOpenFunctionsOutputDto) ctx.get(Constants.OPEN_FUNCTION);
		ctx.setRouteHost(getUrl(outputDto.getUrl())); // 将请求重新指定

		logger.info("将请求路由映射到{}", outputDto.getUrl());
		return null;
	}

	@Override
	public String filterType() {
		return Constants.ROUTE_FILTER;
	}

	@Override
	public int filterOrder() {
		return FILTER_ORDER;
	}

	private URL getUrl(String target) {
		try {
			return new URL(target);
		} catch (MalformedURLException ex) {
			throw new IllegalStateException("Target URL is malformed", ex);
		}
	}
}
